<template>
  <div class="researcher-projects">
    <div class="page-header">
      <h1>我的研究项目</h1>
      <div class="user-role">
        <i class="el-icon-user"></i> 您的身份：<strong class="role-researcher">研究者</strong>
      </div>
    </div>
    
    <div class="action-bar">
      <button @click="createNewProject" class="create-button">
        <i class="el-icon-plus"></i> 创建新项目
      </button>
    </div>
    
    <!-- 加载和错误处理 -->
    <div v-if="loading" class="loading-container">
      <div class="spinner"></div>
      <p>加载项目中...</p>
    </div>
    
    <div v-else-if="error" class="error-container">
      <p>{{ error }}</p>
      <button @click="fetchMyProjects" class="retry-button">重试</button>
    </div>
    
    <div v-else>
      <!-- 项目统计 -->
      <div class="statistics-cards">
        <div class="stat-card">
          <div class="stat-value">{{ myProjects.length }}</div>
          <div class="stat-label">我的项目总数</div>
        </div>
        <div class="stat-card">
          <div class="stat-value">{{ activeProjects.length }}</div>
          <div class="stat-label">进行中项目</div>
        </div>
        <div class="stat-card">
          <div class="stat-value">{{ completedProjects.length }}</div>
          <div class="stat-label">已完成项目</div>
        </div>
      </div>
      
      <!-- 项目筛选 -->
      <div class="filter-tabs">
        <button 
          :class="['filter-tab', { active: activeFilter === 'all' }]" 
          @click="activeFilter = 'all'"
        >
          全部项目
        </button>
        <button 
          :class="['filter-tab', { active: activeFilter === 'active' }]" 
          @click="activeFilter = 'active'"
        >
          进行中
        </button>
        <button 
          :class="['filter-tab', { active: activeFilter === 'completed' }]" 
          @click="activeFilter = 'completed'"
        >
          已完成
        </button>
      </div>
      
      <!-- 项目列表 -->
      <div v-if="filteredProjects.length === 0" class="no-projects">
        <p>暂无{{ filterLabel }}项目</p>
      </div>
      
      <div v-else class="projects-list">
        <div v-for="project in filteredProjects" :key="project.id" class="project-card">
          <div class="project-header">
            <h3 class="project-title">{{ project.title }}</h3>
            <div :class="['status-badge', getStatusClass(project)]">
              {{ getStatusText(project) }}
            </div>
          </div>
          
          <p class="project-description">{{ truncateText(project.description, 150) }}</p>
          
          <div class="project-meta">
            <div class="meta-item">
              <i class="el-icon-time"></i> 创建于: {{ formatDate(project.createdAt) }}
            </div>
            <div class="meta-item">
              <i class="el-icon-user"></i> 参与者: {{ project.participantsCount || 0 }}人
            </div>
          </div>
          
          <div class="project-actions">
            <button @click="viewProject(project.id)" class="btn btn-primary">
              <i class="el-icon-view"></i> 查看详情
            </button>
            <button 
              v-if="!project.isCompleted && !project.isDeleted" 
              @click="editProject(project.id)" 
              class="btn btn-secondary"
            >
              <i class="el-icon-edit"></i> 编辑
            </button>
            <button 
              v-if="!project.isDeleted" 
              @click="confirmDelete(project)" 
              class="btn btn-danger"
            >
              <i class="el-icon-delete"></i> 删除
            </button>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 删除确认弹窗 -->
    <div v-if="showDeleteConfirm" class="modal">
      <div class="modal-content">
        <div class="modal-header">
          <h3>确认删除项目</h3>
          <button class="close-btn" @click="showDeleteConfirm = false">&times;</button>
        </div>
        <div class="modal-body">
          <p>您确定要删除 <strong>{{ projectToDelete?.title }}</strong> 吗？此操作不可逆。</p>
          <div class="form-group">
            <label for="deleteReason">删除原因:</label>
            <textarea id="deleteReason" class="form-control" v-model="deleteReason" rows="3" placeholder="请输入删除原因"></textarea>
          </div>
        </div>
        <div class="form-actions">
          <button class="btn btn-secondary" @click="showDeleteConfirm = false">取消</button>
          <button class="btn btn-danger" @click="submitDelete" :disabled="!deleteReason.trim() || isDeleting">
            {{ isDeleting ? '删除中...' : '确认删除' }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters, mapActions } from 'vuex'

export default {
  name: 'ResearcherProjects',
  data() {
    return {
      loading: true,
      error: null,
      activeFilter: 'all', // 'all', 'active', 'completed'
      projectToDelete: null,
      showDeleteConfirm: false,
      deleteReason: '',
      isDeleting: false
    }
  },
  computed: {
    ...mapGetters({
      isAuthenticated: 'auth/isAuthenticated',
      isResearcher: 'auth/isResearcher',
      currentUser: 'auth/currentUser'
    }),
    
    // 获取当前用户创建的所有项目
    myProjects() {
      const allProjects = this.$store.state.projects || [];
      return allProjects.filter(p => 
        p.creatorId === this.currentUser?.id || 
        p.researcherId === this.currentUser?.id
      );
    },
    
    // 活跃项目
    activeProjects() {
      return this.myProjects.filter(p => !p.isCompleted && !p.isDeleted);
    },
    
    // 已完成项目
    completedProjects() {
      return this.myProjects.filter(p => p.isCompleted && !p.isDeleted);
    },
    
    // 根据当前筛选条件获取项目
    filteredProjects() {
      switch(this.activeFilter) {
        case 'active':
          return this.activeProjects;
        case 'completed':
          return this.completedProjects;
        default:
          return this.myProjects;
      }
    },
    
    // 当前筛选标签
    filterLabel() {
      switch(this.activeFilter) {
        case 'active': return '进行中';
        case 'completed': return '已完成';
        default: return '';
      }
    }
  },
  created() {
    // 检查用户权限
    if (!this.isAuthenticated || !this.isResearcher) {
      this.$router.push('/login');
      return;
    }
    
    this.fetchMyProjects();
  },
  methods: {
    ...mapActions({
      fetchProjects: 'fetchProjects',
      deleteProject: 'deleteProject'
    }),
    
    createNewProject() {
      // 直接导航到创建项目页面
      this.$router.push('/create-project');
    },
    
    async fetchMyProjects() {
      this.loading = true;
      this.error = null;
      
      try {
        // 获取所有项目，在前端进行筛选
        await this.fetchProjects();
      } catch (error) {
        this.error = '加载项目失败，请稍后重试';
        console.error('获取项目列表失败:', error);
      } finally {
        this.loading = false;
      }
    },
    
    formatDate(dateString) {
      if (!dateString) return '未知日期';
      
      try {
        const date = new Date(dateString);
        if (isNaN(date.getTime())) return '无效日期';
        
        return date.toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit'
        }).replace(/\//g, '-');
      } catch (error) {
        console.error('日期格式化错误:', error);
        return '无效日期';
      }
    },
    
    getStatusText(project) {
      if (project.isDeleted) return '已删除';
      if (project.isCompleted) return '已完成';
      return '进行中';
    },
    
    getStatusClass(project) {
      if (project.isDeleted) return 'status-deleted';
      if (project.isCompleted) return 'status-completed';
      return 'status-active';
    },
    
    truncateText(text, maxLength) {
      if (!text) return '';
      if (text.length <= maxLength) return text;
      return text.substring(0, maxLength) + '...';
    },
    
    viewProject(id) {
      this.$router.push(`/project/${id}`);
    },
    
    editProject(id) {
      this.$router.push(`/edit-project/${id}`);
    },
    
    confirmDelete(project) {
      this.projectToDelete = project;
      this.showDeleteConfirm = true;
    },
    
    async submitDelete() {
      if (!this.projectToDelete) return;
      
      try {
        this.isDeleting = true;
        await this.deleteProject({
          id: this.projectToDelete.id,
          reason: this.deleteReason
        });
        
        this.showDeleteConfirm = false;
        this.projectToDelete = null;
        this.deleteReason = '';
        
        // 刷新项目列表
        this.fetchMyProjects();
        
        // 显示成功消息
        this.$message.success('项目删除成功');
      } catch (error) {
        console.error('删除项目失败:', error);
        this.$message.error('删除项目失败: ' + (error.response?.data || error.message || '未知错误'));
      } finally {
        this.isDeleting = false;
      }
    }
  }
}
</script>

<style scoped>
.researcher-projects {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.user-role {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 16px;
  background-color: rgba(0, 85, 164, 0.1);
  padding: 8px 16px;
  border-radius: 20px;
}

.role-researcher {
  color: var(--color-primary);
  font-weight: 600;
}

.action-bar {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 24px;
}

.create-button {
  background-color: var(--color-primary);
  color: white;
  border: none;
  border-radius: 4px;
  padding: 10px 16px;
  cursor: pointer;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: background-color 0.3s;
}

.create-button:hover {
  background-color: var(--color-primary-dark);
}

.statistics-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
  margin-bottom: 24px;
}

.stat-card {
  background-color: white;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  text-align: center;
}

.stat-value {
  font-size: 32px;
  font-weight: 700;
  color: var(--color-primary);
  line-height: 1.2;
}

.stat-label {
  font-size: 14px;
  color: #555;
  margin-top: 4px;
}

.filter-tabs {
  display: flex;
  gap: 12px;
  margin-bottom: 24px;
  border-bottom: 1px solid #eee;
  padding-bottom: 12px;
}

.filter-tab {
  background: none;
  border: none;
  padding: 8px 16px;
  cursor: pointer;
  font-weight: 500;
  color: #555;
  position: relative;
}

.filter-tab.active {
  color: var(--color-primary);
}

.filter-tab.active::after {
  content: '';
  position: absolute;
  bottom: -12px;
  left: 0;
  width: 100%;
  height: 3px;
  background-color: var(--color-primary);
  border-radius: 3px 3px 0 0;
}

.projects-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 24px;
}

.project-card {
  background-color: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  transition: transform 0.3s, box-shadow 0.3s;
}

.project-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.project-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.project-title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.status-badge {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.status-active {
  background-color: rgba(46, 204, 113, 0.2);
  color: #2ecc71;
}

.status-completed {
  background-color: rgba(52, 152, 219, 0.2);
  color: #3498db;
}

.status-deleted {
  background-color: rgba(231, 76, 60, 0.2);
  color: #e74c3c;
}

.project-description {
  padding: 16px;
  margin: 0;
  color: #555;
  line-height: 1.5;
  height: 4.5em;
  overflow: hidden;
}

.project-meta {
  padding: 0 16px;
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.meta-item {
  font-size: 13px;
  color: #777;
  display: flex;
  align-items: center;
  gap: 4px;
}

.project-actions {
  padding: 16px;
  display: flex;
  gap: 8px;
  border-top: 1px solid #f0f0f0;
  margin-top: 8px;
}

.btn {
  padding: 8px 12px;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 4px;
  border: none;
  transition: all 0.2s;
}

.btn-primary {
  background-color: var(--color-primary);
  color: white;
}

.btn-primary:hover {
  background-color: var(--color-primary-dark);
}

.btn-secondary {
  background-color: #f0f0f0;
  color: #333;
}

.btn-secondary:hover {
  background-color: #e0e0e0;
}

.btn-danger {
  background-color: #fff;
  color: #e74c3c;
  border: 1px solid #e74c3c;
}

.btn-danger:hover {
  background-color: #e74c3c;
  color: white;
}

.no-projects {
  text-align: center;
  padding: 40px;
  background-color: #f9f9f9;
  border-radius: 8px;
  color: #777;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px;
}

.spinner {
  width: 40px;
  height: 40px;
  border: 4px solid rgba(0, 85, 164, 0.1);
  border-radius: 50%;
  border-top-color: var(--color-primary);
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.error-container {
  background-color: #ffecec;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 24px;
  color: #e74c3c;
  text-align: center;
}

.retry-button {
  background-color: #e74c3c;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  margin-top: 12px;
  cursor: pointer;
}

.modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background-color: white;
  border-radius: 8px;
  max-width: 500px;
  width: 90%;
  max-height: 90vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.modal-header h3 {
  margin: 0;
  font-size: 18px;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #777;
}

.modal-body {
  padding: 16px;
}

.form-group {
  margin-bottom: 16px;
}

.form-control {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 16px;
  border-top: 1px solid #f0f0f0;
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .projects-list {
    grid-template-columns: 1fr;
  }
  
  .filter-tabs {
    overflow-x: auto;
    padding-bottom: 8px;
  }
}
</style> 